package com.nitty.cash.loop.ui.activity

import android.annotation.SuppressLint
import android.graphics.BitmapFactory
import android.os.CountDownTimer
import android.view.View
import com.nitty.cash.loop.R
import com.nitty.cash.loop.common.CommonActivity
import com.nitty.cash.loop.databinding.UiLimitReviewingBinding
import com.nitty.cash.loop.event.NittyEventData
import com.nitty.cash.loop.event.NittyEventPointType
import com.nitty.cash.loop.ui.contract.IViewContract
import com.nitty.cash.loop.ui.presenter.LimitReviewingPresenter
import com.nitty.cash.loop.utils.NittyTitleBarUtil
import com.nitty.cash.loop.utils.helper.NittyProcessHelper
import org.json.JSONObject
import java.math.BigDecimal

/**
 * NittyCash
 * @Author wwdeng
 * @CreateTime: 2024/12/16 13:41
 * @Annotation：额度审核中
 */
class LimitReviewingAct: CommonActivity(),IViewContract.ILimitReviewingView {
    lateinit var binding: UiLimitReviewingBinding
    private var presenter: LimitReviewingPresenter? = null
    private var countdownTimer: MyCountDownTimer? = null
    //等待时长
    private var countdown = 15

    override fun getNittyRootView(): View? {
        binding = UiLimitReviewingBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initNittyView() {
        NittyTitleBarUtil.setStatusBarLightMode(this, false)
        binding.limitReviewingLayout.setPadding(0,NittyTitleBarUtil.getStatusBarHeight(),0,0)
        binding.nestedScrollView.visibility = View.GONE
    }

    override fun initNittyListener() {
        //返回
        binding.imgLimitReviewingBack.setOnClickListener {
            finish()
        }
        binding.imgLimitReviewingCustomer.setOnClickListener {
            showCustomerDialog("Limit Reviewing Page")
            addEventPointRequestAction(NittyEventPointType.CLICK.NITTY_CLICK_CUSTOMER,"Limit Reviewing Page")
        }
        binding.btnWithdrawNow.setOnClickListener {
            presenter?.checkNittyLimitReviewingPermissionsAgree()
        }
    }

    override fun loadNittyData() {
        if (presenter == null){
            presenter = LimitReviewingPresenter(this)
        }
        presenter?.queryNittyCreditStatusAction()
    }

    /**
     * 额度审核中
     */
    @SuppressLint("SetTextI18n")
    override fun showLimitReviewingViews() {
        binding.nestedScrollView.visibility = View.VISIBLE
        binding.imgLimitReviewingBack.visibility = View.GONE
        binding.textLimitReviewingExpirse.text = String.format(getString(R.string.withdraw_expires),"**/**/****")
        binding.imgLimitReviewingExpirseTips.visibility = View.GONE

        binding.textLimitReviewingAmount.text = "***,***"
        binding.textLimitReviewingMinAmount.text = "0"
        binding.textLimitReviewingMaxAmount.text = "**,***"
        //动画效果
        binding.limitReviewingSeekBar.max = 1000
        binding.limitReviewingSeekBar.showAnimation(binding.limitReviewingSeekBar.max, 0, 1000)
        //禁止拖拽
        binding.limitReviewingSeekBar.isEnabledDrag = false
        //设置游标
        binding.limitReviewingSeekBar.setCursorThumbBitmap(BitmapFactory.decodeResource(resources, R.mipmap.nitty_amount_cursor_normal))

        binding.limitReviewingSeekbarLayout.setBackgroundResource(R.mipmap.nitty_limit_reviewing_top_bg)
        binding.limitReviewingActivatedLayout.visibility = View.VISIBLE
        binding.limitReviewingWithdrawLayout.visibility = View.GONE

        binding.textLimitReviewingTips.text = getString(R.string.limit_reviewing_not_leave)
        binding.textLimitReviewingCountdown.visibility = View.VISIBLE
        binding.textLimitReviewingCountdown.text = "$countdown s"

        //启动倒计时
        startCountdownTimer()
    }

    /**
     * 额度审核成功
     */
    override fun showLimitSuccessViews(data: JSONObject) {
        binding.nestedScrollView.visibility = View.VISIBLE
        binding.imgLimitReviewingBack.visibility = View.VISIBLE
        binding.textLimitReviewingExpirse.text = String.format(getString(R.string.withdraw_expires), NittyProcessHelper.getAuthCreditExpireDate())
        binding.imgLimitReviewingExpirseTips.visibility = View.VISIBLE

        val availableAmount = BigDecimal(data.optString("availableAmount")).stripTrailingZeros().toPlainString()
        val minAmount = BigDecimal(data.optString("minAmount")).stripTrailingZeros().toPlainString()
        val maxAmount = BigDecimal(data.optString("maxAmount")).stripTrailingZeros().toPlainString()

        binding.textLimitReviewingAmount.text = availableAmount
        binding.textLimitReviewingMinAmount.text = minAmount
        binding.textLimitReviewingMaxAmount.text = maxAmount
        //动画效果
        binding.limitReviewingSeekBar.max = maxAmount.toInt()
        binding.limitReviewingSeekBar.showAnimation(0, binding.limitReviewingSeekBar.max, 1000)
        //禁止拖拽
        binding.limitReviewingSeekBar.isEnabledDrag = false
        //设置游标
        binding.limitReviewingSeekBar.setCursorThumbBitmap(BitmapFactory.decodeResource(resources, R.mipmap.nitty_amount_cursor_pressed))

        binding.limitReviewingSeekbarLayout.setBackgroundResource(R.mipmap.nitty_withdraw_seekbar_top_bg)
        binding.limitReviewingActivatedLayout.visibility = View.GONE
        binding.limitReviewingWithdrawLayout.visibility = View.VISIBLE

        binding.textLimitReviewingTips.text = getString(R.string.limit_reviewing_success)
        binding.textLimitReviewingCountdown.visibility = View.GONE

        if (countdownTimer != null){
            countdownTimer?.cancel()
        }
    }

    /**
     * 额度审核失败
     */
    override fun showLimitFailedViews() {
        onIntent(LimitRejectedAct::class.java)
        finish()
    }

    /**
     * 申贷
     */
    override fun showLimitApplyPage() {
        ApplyAct.start(this)
        finish()
    }

    override fun showLimitPermissionPage() {
        onIntent(PermissionAppListSmsAct::class.java)
        finish()
    }

    /**
     * 开启倒计时
     */
    private fun startCountdownTimer(){
        if (countdownTimer == null){
            countdownTimer = MyCountDownTimer(this,countdown.toLong() * 1000,1000)
        }
        countdownTimer?.start()
    }

    @SuppressLint("SetTextI18n")
    private fun showLimitCountdownText(){
        binding.textLimitReviewingCountdown.text = "$countdown s"
    }

    private fun showLimitCountdownComplete(){
        showNittyLoading()
        publishEventData(NittyEventData(NittyEventData.TYPE.NITTY_PROCESS_REFRESH))
    }

    class MyCountDownTimer(private val act: LimitReviewingAct,millisInFuture: Long, countDownInterval: Long): CountDownTimer(millisInFuture, countDownInterval) {
        override fun onTick(millisUntilFinished: Long) {
            // 这里每隔一段时间（定时器间隔）会被调用
            // 可以在这里更新UI，显示剩余时间
            act.countdown = (millisUntilFinished / 1000).toInt()
            act.showLimitCountdownText()
        }
        override fun onFinish() {
            // 倒计时完成时被调用
            act.showLimitCountdownComplete()
        }
    }

    override fun onNittyPublishEvent(event: NittyEventData) {
        super.onNittyPublishEvent(event)
        if (event.eventType == NittyEventData.TYPE.NITTY_PROCESS_REFRESHED){
            presenter?.queryNittyCreditStatusAction()
        }
    }

    override fun onStart() {
        super.onStart()
        addEventPointRequestAction(NittyEventPointType.PAGE.NITTY_PAGE_CREDIT_REVIEWING_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(NittyEventPointType.PAGE.NITTY_PAGE_CREDIT_REVIEWING_END)
        if (countdownTimer != null){
            countdownTimer?.cancel()
            countdownTimer = null
        }
    }
}